package top.cardone.validator.func;

import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import top.cardone.context.util.MessageUtils;
import top.cardone.core.util.func.Func4;

import java.util.Map;
import java.util.Objects;

/**
 * Created by Administrator on 2016/9/19.
 */
@Log4j2
public class RequiredValidatorFunc implements Func4<String, Map<String, Object>, String, Object, Object> {
	@Setter
	protected String code = "validator.required";

	@Setter
	protected String readOneMessageFuncBeanId = "readOneMessageFunc";

	@Override
	public String func(Map<String, Object> map, String key, Object rule, Object message) {
		log.debug(this.code + ":" + key);

		if (rule instanceof Boolean) {
			if (BooleanUtils.isFalse((Boolean) rule)) {
				return null;
			}
		}

		Object val = MapUtils.getObject(map, key);

		if (!Objects.isNull(val)) {
			if (!(val instanceof String)) {
				return null;
			} else {
				String valString = (String) val;

				if (StringUtils.isNotBlank(valString)) {
					return null;
				}
			}
		}

		return this.getMessage(message, new Object[]{});
	}

	protected String getMessage(Object message, Object[] args) {
		if (message instanceof String) {
			return (String) message;
		}

		Map<String, String> messageMap = (Map<String, String>) message;

		String code = StringUtils.defaultString(MapUtils.getString(messageMap, "code"), this.code);

		String defaultMessage = MapUtils.getString(messageMap, "defaultMessage");

		return MessageUtils.getMessage(code, args, defaultMessage, this.readOneMessageFuncBeanId);
	}
}